package com.backwaveweibo.bww.controller;

import com.backwaveweibo.bww.entity.Comments;
import com.backwaveweibo.bww.entity.Weibo;
import com.backwaveweibo.bww.service.CommentsService;
import com.backwaveweibo.bww.utils.Result;
import com.backwaveweibo.bww.utils.ResultCode;
import com.backwaveweibo.bww.utils.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author GHW : RD-Kelsey
 * @description 评论-表述层
 * @date 2020/6/13
 */

@RestController
@RequestMapping("comments")
@Slf4j
public class CommentsController {

    @Resource
    private CommentsService commentsService;

    /**
     * 发表评论
     * 必须传入字段：content,weiboId
     * 需要权限: 用户 | 管理员
     *
     * @param comments 实体
     * @return 统一返回结果集
     */
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @PostMapping("add")
    public Result addComments(@RequestBody Comments comments) {
        if (comments != null) {
            boolean result = commentsService.addComments(comments);
            if (result) {
                return ResultGenerator.genSuccessResult(ResultCode.SUCCESS, "评论发表成功", true);
            } else {
                return ResultGenerator.genFailResult(ResultCode.FAIL, "该条微博不存在！", false);
            }
        }
        return ResultGenerator.genFailResult(ResultCode.FAIL, "评论内容为空", false);
    }

    /**
     * 查询评论接口 ===> 无参数，或任意允许的参数，均可
     * <p>
     * 允许的参数：
     * weibo.weiboId：评论所在的微博的id
     * commentsId：评论的id
     *
     * @return 统一返回结果集
     */
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @GetMapping("get")
    public Result getCommentsInfoByCondition(@RequestParam(value = "weiboId", required = false) Long weiboId) {
        List<Comments> localComments = commentsService.getCommentsByCondition(new Comments().setWeibo(new Weibo().setWeiboId(weiboId)));
        if (localComments != null) {
            return ResultGenerator.genSuccessResult(ResultCode.SUCCESS, "评论查询成功", localComments);
        }
        return ResultGenerator.genFailResult(ResultCode.FAIL, "没有查询到评论", false);
    }

    /**
     * 删除评论
     *
     * @param commentsId ==> 评论id，必须
     * @return 统一返回结果集
     */
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @GetMapping("delete")
    public Result deleteComments(@RequestParam("commentsId") Long commentsId) {
        boolean result = commentsService.deleteComments(commentsId);
        if (result) {
            return ResultGenerator.genSuccessResult(ResultCode.SUCCESS, "删除评论成功", true);
        }
        return ResultGenerator.genFailResult(ResultCode.FAIL, "删除评论失败", false);
    }
}
